package com.yate.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yate.auth.service.SysMenuService;
import com.yate.auth.service.SysUserService;
import com.yate.common.MD5.MD5;
import com.yate.common.config.exception.BusinessException;
import com.yate.common.jwt.JwtHelper;
import com.yate.common.result.Result;
import com.yate.model.system.SysUser;
import com.yate.vo.system.LoginVo;
import com.yate.vo.system.RouterVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ Tool：IntelliJ IDEA
 * @ Author：云生
 * @ Date：2024-11-30-1:46
 * @ Version：1.0
 * @ Description：
 */
@Api(tags = "后台登录管理")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysMenuService sysMenuService;

    /**
     * @Author: yate
     * @Description:登录页面
     * @param:
     * @return:
     */
    @ApiOperation("登录")
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo) {
        //1.获取用户名和密码
        //2.根据用户名查询数据库，校验用户名和密码
        String username = loginVo.getUsername();
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, username);
        SysUser sysUser = sysUserService.getOne(queryWrapper);

        //2.1.判断用户名是否存在
        if (sysUser == null) {
            throw new BusinessException(201, "用户名不存在");
        }

        //2.2.判断密码是否正确
        //从数据库中获取MD5加密后的密码
        String password_db = sysUser.getPassword();
        //从前端获取输入的密码
        String password_input = MD5.encrypt(loginVo.getPassword());

        if (!password_db.equals(password_input)) {
            {
                throw new BusinessException(201, "密码错误");
            }
        }
        //2.3.判断用户是否被禁用  1  可用 0 禁用

        if (sysUser.getStatus().intValue() == 0) {
            throw new BusinessException(201, "用户被禁用");
        }

        //3.使用jwt根据用户id和用户名生成token字符串
        String token = JwtHelper.createToken(sysUser.getId(), sysUser.getUsername());
        //4.返回token字符串
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        return Result.success(map);
    }


    //info页面

    /**
     * @Author: yate
     * @Description: 获取用户信息
     * @param:
     * @return:
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public Result info(HttpServletRequest request) {

        //1.从请求头获取用户信息（获取请求头token字符串）
        String token = request.getHeader("token");

        //2.从token字符串获取用户id或用户名
        Long userId = JwtHelper.getUserId(token);

        //3.根据用户id查询数据库，获取用户信息
        SysUser sysUser = sysUserService.getById(userId);

        //4.根据用户id获取用户可以操作的菜单列表
        //查询数据库动态构建路由结构，进行显示
        List<RouterVo> routerList = sysMenuService.findUserMenuListByUserId(userId);

        //5.根据用户id获取用户可以操作的按钮列表
        List<String> permsList = sysMenuService.findUserPermsByUserId(userId);

        //6.返回用户信息，菜单列表，按钮列表
        Map<String, Object> map = new HashMap<>();
        map.put("roles", "[admin]");
        map.put("name", sysUser.getName());
        map.put("avatar", "https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");

        //返回用户可以操作的菜单
        map.put("routers", routerList);

        //返回用户可以操作的按钮
        map.put("buttons", permsList);

        return Result.success(map);

    }

    //logout页面

    /**
     * @Author: yate
     * @Description: 退出
     * @param:
     * @return:
     */
    @ApiOperation("退出")
    @PostMapping("/logout")
    public Result logout() {
        return Result.success();
    }
}
